package com.zbl.springdemo.bean.lifecycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;

@Component
public class InstantiationAwareBeanPostProcessorDemo implements InstantiationAwareBeanPostProcessor {

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if (!"beanDemo".equals(beanName)) {
            return null;
        }
        // 不会执行后面的spring创建bean的过程
        System.out.println("对象实例化前置操作");
        try {
            return beanClass.getConstructors()[0].newInstance();
        } catch (Exception e) {
            return new Object();
        }
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if (!"beanDemo".equals(beanName)) {
            return true;
        }
        System.out.println("对象实例化后置操作");
        return false;
    }
}
